package session

import (
	"sync"
	"time"
)

var sessionManage manage

func init() {
	sessionManage = manage{
		Lock:        sync.RWMutex{},
		MaxLifeTime: -1, //s
		Sessions:    make(map[string]*sessionBean),
	}
	loadSessionFormDB()
	if sessionManage.MaxLifeTime > 0 {
		go sessionManage.gc()
	}
}

/*Session会话管理*/
type manage struct {
	CookieName  string                  //客户端cookie名称
	Lock        sync.RWMutex            //互斥(保证线程安全)
	MaxLifeTime int64                   //垃圾回收时间
	Sessions    map[string]*sessionBean //保存session的指针[sessionID] = sessionBean
}

//GC回收
func (sm *manage) gc() {
	sm.Lock.Lock()
	defer sm.Lock.Unlock()
	for sessionID, session := range sm.Sessions {
		//删除超过时限的session
		if session.IsExpire() {
			delete(sm.Sessions, sessionID)
			deleteSessionToDB(session.SessionID)
		}
	}
	//定时回收
	time.AfterFunc(time.Duration(sm.MaxLifeTime)*time.Second, func() { sm.gc() })
}
func CreateNewSession(userId string) (*sessionBean, error) {
	newSession := newSession(userId)
	newSession.MaxLifeTime = sessionManage.MaxLifeTime
	sessionManage.Sessions[newSession.SessionID] = newSession
	return newSession, addSessionToDB(newSession)
}
func addSession(s *sessionBean) {
	sessionManage.Sessions[s.SessionID] = s
}
func GetSession(sessionID string) (*sessionBean, bool) {
	sessionManage.Lock.Lock()
	defer sessionManage.Lock.Unlock()
	session, ok := sessionManage.Sessions[sessionID]
	return session, ok
}
func DeleteSession(sessionID string) error {
	sessionManage.Lock.Lock()
	defer sessionManage.Lock.Unlock()
	delete(sessionManage.Sessions, sessionID)
	return deleteSessionToDB(sessionID)

}
